package com.by.basicweb.converter;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipHttpMessageConverter extends AbstractHttpMessageConverter<byte[]> {

    public ZipHttpMessageConverter() {
        super(new MediaType("application", "zip", StandardCharsets.UTF_8));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return byte[].class.isAssignableFrom(clazz);
    }

    @Override
    protected byte[] readInternal(Class<? extends byte[]> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        throw new UnsupportedOperationException("Deserializing from ZIP format is not supported");
    }

    @Override
    protected void writeInternal(byte[] bytes, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
             ZipOutputStream zos = new ZipOutputStream(outputMessage.getBody(), StandardCharsets.UTF_8)) {

            ZipEntry entry = new ZipEntry("file"); // You can customize the entry name
            zos.putNextEntry(entry);
            zos.write(bytes);
            zos.closeEntry();

        } catch (IOException e) {
            throw new IOException("Failed to write bytes as zip", e);
        }
    }
}
